package com.net.xpay.core.manager.impl.collect;

import com.google.common.base.Preconditions;
import com.net.xpay.core.manager.collect.CollectionOrderManager;
import com.net.common.annotation.WriteTransactional;
import com.net.common.dao.BasicMapper;
import com.net.common.dao.Page;
import com.net.common.manager.AbstractVersionedManager;
import com.net.noah.core.service.SerialNumberService;
import com.net.xpay.core.dao.collect.CollectionOrderMapper;
import com.net.xpay.core.domain.collect.CollectionOrder;
import com.net.xpay.core.model.CollectionOrderSearchModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;

import java.time.LocalDateTime;
import java.util.List;


@Component
public class CollectionOrderManagerImpl extends AbstractVersionedManager<CollectionOrder> implements CollectionOrderManager {

    @Autowired
    private CollectionOrderMapper mapper;

    @Autowired
    private SerialNumberService serialNumberService;


    @Override
    protected BasicMapper<Long, CollectionOrder> getMapper() {
        return mapper;
    }



    @Override
    @WriteTransactional(propagation = Propagation.SUPPORTS)
    public int save(CollectionOrder obj) {
        Preconditions.checkArgument(obj.getId() == null);
        obj.setId(serialNumberService.getLongSerialNumber(getTableFullName()));

        return super.save(obj);
    }

    @Override
    public List<CollectionOrder> search(CollectionOrderSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        Page page = new Page(searchModel);
        page.addOrder("id", "desc");
        return nonEmptyList(mapper.search(searchModel, page));
    }

    @Override
    public long searchCount(CollectionOrderSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        return mapper.searchCount(searchModel);
    }

    @Override
    public List<CollectionOrder> findByIds(List<Long> ids) {
        Preconditions.checkArgument(CollectionUtils.isNotEmpty(ids));
        return nonEmptyList(mapper.findByIds(ids));
    }

    @Override
    public int batchUpdate(List<CollectionOrder> orders) {
        if (CollectionUtils.isEmpty(orders)) {
            return 0;
        }
        for (CollectionOrder record : orders) {
            LocalDateTime now = LocalDateTime.now();
            record.setModifyTime(now);
            record.setVersion(record.getVersion() + 1L);
        }

        return mapper.batchUpdate(orders);
    }
}
